﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using LYT.Dal;

namespace LYT.Biz
{
    public class Factory
    {
        public static string GetItemsOnsale(string token, int pageindex = 1, int pagesize = 40)
        {
            IDictionary<string, string> param = new Dictionary<string, string>();
            param.Add(ConstParam.PARAM_KEY_CLIENTID, ConstParam.PARAM_VALUE_CLIENTID);
            param.Add(ConstParam.PARAM_KEY_VERSION, ConstParam.PARAM_VALUE_VERSION);
            param.Add(ConstParam.PARAM_KEY_FORMAT, ConstParam.PARAM_VALUE_FORMAT);
            param.Add(ConstParam.PARAM_KEY_TOKEN, token);

            param.Add(ConstParam.PARAM_KEY_METHOD, ConstTaobaoMethod.ITEMS_ONSALE);
            param.Add(ConstParam.PARAM_KEY_FIELDS, ConstTaobaoMethod.ITEMS_ONSALE_FIELDS);

            string restb = Util.Post(ConstTaobaoMethod.SERVER_URL, param);

            //string restb = @"{""items_onsale_get_response"":{""items"":{""item"":[{""num_iid"":1500023591130,""price"":""100.00"",""title"":""沙箱测试:徐亮""},{""num_iid"":1500023591129,""price"":""100.00"",""title"":""沙箱测试:陈功""}]},""total_results"":12}}";

            Json.Serialization.JavaScriptSerializer s = new Json.Serialization.JavaScriptSerializer();
            ResponeData o = s.Deserialize<ResponeData>(restb);
            if (o != null && o.items_onsale_get_response != null && o.items_onsale_get_response.items != null)
            {
                o.items_onsale_get_response.pageindex = pageindex;
                o.items_onsale_get_response.pagesize = pagesize;
                o.items_onsale_get_response.pagecount = (int)Math.Ceiling((Double)o.items_onsale_get_response.total_results / (Double)o.items_onsale_get_response.pagesize);
                foreach (var it in o.items_onsale_get_response.items.item)
                {
                    using (dataEntities cxt = new dataEntities(ConstData.ConnectionString))
                    {
                        var litedate = cxt.item.Where(e => e.num_iid == it.num_iid).FirstOrDefault();
                        if (litedate != null)
                            it.cost = litedate.cost;
                    }
                }
            }

            return s.Serialize(o);
        }
    }
}
